package cn.com.connext.scrm.utils.wechat;

import cn.com.connext.scrm.service.dto.WechatConfig;

import java.security.MessageDigest;
import java.util.*;

public class CardSignature {
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    /**
     * 卡券签名
     *
     * @param cardId 卡券第三方id
     * @param appid  appid
     * @return
     * @throws Exception
     */
    public static WechatConfig getCardSignature(String cardId, String appid, String accessToken) throws Exception {
        WechatConfig config = new WechatConfig();
        config.setNonceStr(UUID.randomUUID().toString().replaceAll("-", ""));
        // 时间戳
        config.setTimestamp(Long.toString(System.currentTimeMillis() / 1000));
        // 当前网页的URL，不包含#及其后面部分 主微信appid
        config.setAppId(appid);

//        StringBuffer curUrl = request.getRequestURL();
//        String params = request.getQueryString();
//        if (!StringUtils.isBlank(params)) {
//            curUrl = curUrl.append("?").append(params);
//        }
//        config.setUrl(curUrl.toString());

        //获取jsapi_ticket
        Map<String, String> jsApiTicketMap = JsApiTicketUtils.getWxCardJsApiTicket(accessToken);
        String jsapiTicket = jsApiTicketMap.get("wx_card_jsapi_ticket");

        List<String> list = new ArrayList<>();
        list.add(jsapiTicket);
        list.add(config.getNonceStr());
        list.add(config.getTimestamp());
        list.add(cardId);

        Collections.sort(list);
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            sBuffer.append(list.get(i));
        }
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(sBuffer.toString().getBytes("UTF-8"));

        config.setSignature(byteToHex(crypt.digest()));
        return config;
    }
}
